//
//  ScrollView.m
//  Objective-C
//
//  Created by 陆承东 on 2018/7/1.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "ScrollView.h"

@implementation ScrollView

+ (Class)layerClass {
    return [CAScrollLayer class];
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self setUp];
}

- (instancetype)init {
    self = [super init];
    
    if (self) {
        [self setUp];
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        [self setUp];
    }
    
    return self;
}

- (void)setUp {
    // enable clipping
    self.layer.masksToBounds = true;
    
    // attach pan gesture recognizer
    UIPanGestureRecognizer *recognizer = nil;
    recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:recognizer];
}

- (void)pan:(UIPanGestureRecognizer *)recognizer {
    // get the offset by subtracting the pan gesture
    // translation from the current bounds origin
    CGPoint offset = self.bounds.origin;
    offset.x -= [recognizer translationInView:self].x;
    offset.y -= [recognizer translationInView:self].y;
    
    NSLog(@"translationInView: %@", NSStringFromCGPoint([recognizer translationInView:self]));
    NSLog(@"offset: %@", NSStringFromCGPoint(offset));
    
    // scroll the layer
    [(CAScrollLayer *)self.layer scrollToPoint:offset];
    
    // reset the pan gesture translation
    [recognizer setTranslation:CGPointZero inView:self];
}

@end
